package cn.fql.pet.service.impl;

import cn.fql.basic.exception.BusinessException;
import cn.fql.basic.service.IBaiduAiAuditService;
import cn.fql.basic.util.*;
import cn.fql.org.domain.Employee;
import cn.fql.org.domain.Shop;
import cn.fql.org.mapper.EmployeeMapper;
import cn.fql.org.mapper.ShopMapper;
import cn.fql.order.domain.OrderPetAcquisition;
import cn.fql.pet.domain.SearchMasterMsg;
import cn.fql.pet.domain.SearchMasterMsgAuditLog;
import cn.fql.pet.dto.OrderDto;
import cn.fql.order.mapper.OrderPetAcquisitionMapper;
import cn.fql.pet.mapper.SearchMasterMsgAuditLogMapper;
import cn.fql.pet.mapper.SearchMasterMsgMapper;
import cn.fql.pet.query.SearchMasterMsgQuery;
import cn.fql.pet.service.ISearchMasterMsgService;
import cn.fql.basic.service.impl.BaseServiceImpl;
import cn.fql.user.domain.Logininfo;
import cn.fql.user.domain.User;
import cn.fql.user.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;

/**
 * 业务实现类：
 */
@Service
public class SearchMasterMsgServiceImpl extends BaseServiceImpl<SearchMasterMsg> implements ISearchMasterMsgService {

    @Autowired
    private IBaiduAiAuditService baiduAiAuditService;
    @Autowired
    private SearchMasterMsgMapper searchMasterMsgMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private EmployeeMapper employeeMapper;
    @Autowired
    private ShopMapper shopMapper;
    @Autowired
    private SearchMasterMsgAuditLogMapper searchMasterMsgAuditLogMapper;
    @Autowired
    private OrderPetAcquisitionMapper orderPetAcquisitionMapper;

    @Override
    public AjaxResult publish(SearchMasterMsg searchMasterMsg, HttpServletRequest request) {
        // name: '小七',
        // price: 10,
        // age: 3,
        // gender: 1,
        // coatColor: '黑色',
        // resources: null,
        // petType: 1,
        // address: null,
        // title: '小七寻主'
        // UserId -发布人 - request获取
        // shopId - 分配给哪一个店铺，审核通过之后再分配 - 现在不用管
        // note - 发布寻主消息的说明 - 不用管

        //一：保存到数据库：如何审核失败 - 可以以修改的方式重新提交审核资料/发布寻主消息
        Logininfo logininfo = LoginContext.getLogininfo(request);
        User user  = userMapper.findByLogininfoId(logininfo.getId());
        searchMasterMsg.setUserId(user.getId());
        //添加的时候 有自增id
        searchMasterMsgMapper.save(searchMasterMsg);

        //二：智能审核
        Boolean boo1 = baiduAiAuditService.textAudit(searchMasterMsg.getName() + searchMasterMsg.getTitle());
        Boolean boo2 = baiduAiAuditService.imageAudit(searchMasterMsg.getResources());

        if(boo1 && boo2){
            //三：审核通过：1.改state=1 2.分配最近50公里以内的店铺 3.记录审核日志 4.发短信或邮箱告诉店铺管理员去接回宠物
            //1.改state=1
            searchMasterMsg.setState(1);
            //2.分配最近50公里以内的店铺
            List<Shop> shops = shopMapper.findAll();

            System.out.println(searchMasterMsg.getAddress());

            Point point = DistanceUtils.getPoint(searchMasterMsg.getAddress());
            Shop nearestShop = DistanceUtils.getNearestShop(point, shops);
            if(nearestShop == null){
                searchMasterMsg.setState(3);
            }else{
                searchMasterMsg.setShopId(nearestShop.getId());
            }
            //修改信息
            searchMasterMsgMapper.update(searchMasterMsg);
            //3.记录审核日志
            SearchMasterMsgAuditLog log = new SearchMasterMsgAuditLog();
            log.setMsgId(searchMasterMsg.getId());
            log.setState(1);
            //审核通过
            log.setNote("审核通过！");
            //4.发短信或邮箱告诉店铺管理员去接回宠物
            Employee employee = employeeMapper.findById(nearestShop.getId());
            //SmsUtils.sendSms(employee.getPhone(),"你有新的订单，请在3天之内去【"+searchMasterMsg.getAddress()+"】接回宠物")
            System.out.println("你有新的订单，请在3天之内去【"+searchMasterMsg.getAddress()+"】接回宠物");
            return new AjaxResult();
        }else {
            //四：审核失败: 1.改状态state=-1 2.记录审核日志 3.发短信或邮箱告诉用户重新修改资料再分布
            //1.改状态state=-1
            searchMasterMsg.setState(-1);
            searchMasterMsgMapper.update(searchMasterMsg);
            //2.记录审核日志
            SearchMasterMsgAuditLog log = new SearchMasterMsgAuditLog();
            log.setMsgId(searchMasterMsg.getId());
            log.setState(0);
            //审核失败
            log.setNote("审核失败");

            //3.发短信或邮箱告诉用户审核失败，重新修改寻主消息
            //SmsUtils.sendSms(user.getPhone(),"你的消息审核失败，请重新修改之后再发布");
            System.out.println("你的消息审核失败，请重新修改之后再发布");
            return AjaxResult.me().setSuccess(false).setMsg("寻主消息审核失败");
        }
    }

    @Override
    public PageList<SearchMasterMsg> user(SearchMasterMsgQuery query, HttpServletRequest request) {
        //想办法获取用户的id  从登录信息中获取登录信息
        Logininfo logininfo = LoginContext.getLogininfo(request);
        User user = userMapper.findById(logininfo.getId());
        query.setUserId(user.getId());
        return super.queryPage(query);
    }

    @Override
    public PageList<SearchMasterMsg> toHandle(SearchMasterMsgQuery query, HttpServletRequest request) {
        //查询state 为1 的宠物
        query.setState(1);
        //区分平台管理员或店铺管理员
        Logininfo logininfo = LoginContext.getLogininfo(request);
        Employee employee = employeeMapper.findByLogininfoId(logininfo.getId());
        System.out.println(employee);
        if(employee.getShop_id()!= null){
            //不为空 则是店铺管理员
            query.setShopId(employee.getShop_id());
        }
        return super.queryPage(query);
    }

    @Override
    //店铺管理员不能查询以完成的寻主消息：可以通过菜单权限或资源权限来限制
    public PageList<SearchMasterMsg> finish(SearchMasterMsgQuery query, HttpServletRequest request) {
        //查找state为2的数据 也就是已处理的宠物 店铺管理员是不能查看的
        query.setState(2);
        return super.queryPage(query);
    }

    @Override
    //平台管理员或店铺管理员都可以看：寻主池中的消息shopId is null。只要是state=3，shopId就是null
    public PageList<SearchMasterMsg> toSearchMasterPool(SearchMasterMsgQuery query, HttpServletRequest request) {
        //查询寻主池里面的数据
        query.setState(3);

        return super.queryPage(query);
    }

    //拒单
    @Override
    public void reject(Long id) {
        searchMasterMsgMapper.reject(id);
    }
    //接单
    @Override
    public void accept(OrderDto orderDto) {
        //判断当前点击的订单是否被处理
        OrderPetAcquisition dbOrder = orderPetAcquisitionMapper.loadByMsgId(orderDto.getMsgId());
        if(dbOrder!=null){
            throw new BusinessException("该订单正在被处理");
        }
        //二：生成收购订单
        SearchMasterMsg msg = searchMasterMsgMapper.findById(orderDto.getMsgId());
        OrderPetAcquisition order = orderDto2Order(orderDto,msg);
        orderPetAcquisitionMapper.save(order);

        //三：通知接单人 - 发短信
        Employee employee = employeeMapper.findById(orderDto.getHandler());
        SmsUtils.sendSms(employee.getPhone(),"你有新的订单，请在3天内去"+order.getAddress()+"接回宠物");

        System.out.println("你有新的订单，请在3天内去"+order.getAddress()+"接回宠物");

    }

    private OrderPetAcquisition orderDto2Order(OrderDto orderDto, SearchMasterMsg msg) {
        OrderPetAcquisition order = new OrderPetAcquisition();
        String orderSn = CodeGenerateUtils.generateOrderSn(msg.getUserId());
        order.setOrderSn(orderSn);
        order.setDigest(orderDto.getNote());
        //3天后没有接单处理 就自动取消 - 定时器
        order.setLastcomfirmtime(new Date(System.currentTimeMillis() + 3*24*60*60*1000));
        order.setPrice(msg.getPrice());
        //支付类型 - 确认订单了设置
        //宠物的id  -  确认订单之后 接回宠物再设置
        order.setUserId(msg.getUserId());
        order.setShopId(msg.getShopId());
        order.setAddress(msg.getAddress());
        order.setEmpId(orderDto.getHandler());
        order.setSearchMasterMsgId(orderDto.getMsgId());
        return order;
    }
}
